# coding: utf-8
class PostsController < ApplicationController

  # 显示列表
  def list
    # 类别列表
    if(params[:urlname] != nil)
      cate = Common.getCateByUrlName(params[:urlname]) # 获取类别
      if(cate != nil)
        @h1_name = cate[:viewname]
        @posts = Post.where("postdate <= '#{Time.now.in_time_zone().strftime('%Y-%m-%d %H:%M:%S')}'").where(:cateid => cate[:id]).paginate(:page => params[:page]).order('postdate DESC')
        pageData = Common.getPageData[params[:urlname]]
        if(pageData != nil)
          @page_title = pageData['title']
          @page_keywords = pageData['keywords']
          @page_desc = pageData['desc']
        end
      end
    else
      @posts = Post.where("postdate <= '#{Time.now.in_time_zone().strftime('%Y-%m-%d %H:%M:%S')}'").order('postdate DESC').paginate(:per_page => 10, :page => params[:page])
      @posts.total_entries = 100 if(@posts.total_entries > 100)
      @page_title = Common.getPageData['index']['title']
      @page_keywords = Common.getPageData['index']['keywords']
      @page_desc = Common.getPageData['index']['desc']
      @h1_name = '最新笑话'
      @webindex = true if(params[:page] == nil) # 是否为首页
    end
  end

  # 详情页
  def detail
    @post = Post.find(params[:id])
    if(@post != nil)
      # 更新点击次数
      @post.update_column('hit', @post.hit.to_i + 1)
    end
    @page_title = @post.title.dup << ' - ' <<  Common.getCateName(@post.cateid).dup << ' - 逗死了'

    @post_pre = Post.where("postdate > '#{@post.postdate}' and postdate <= '#{Time.now.in_time_zone().strftime('%Y-%m-%d %H:%M:%S')}'").order('postdate ASC').limit(1)
    @post_next = Post.where("postdate < '#{@post.postdate}'").order('postdate desc').limit(1)

    # 本栏目随机笑话
    @CatePosts = Post.select('id, title, cateid').where("cateid = #{@post.cateid}").all(:order=>"RAND()", :limit=>10)

    # 全站随机图片
    @PicPosts = Post.select('id, title, cateid, pic').where("length(pic) > 10 and id < #{@post.id + 100} and id > #{@post.id - 100}").all(:order=>"RAND()", :limit=>4)
  end

  # GET /posts
  # GET /posts.json
  def index

    # 后台权限检测
    return unless checkAdmin

    @posts = Post.paginate(:page => params[:page]).order('postdate DESC')

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end

  # GET /posts/1
  # GET /posts/1.json
  def show

    # 后台权限检测
    return unless checkAdmin

    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @post }
    end
  end

  # GET /posts/new
  # GET /posts/new.json
  def new

    # 后台权限检测
    return unless checkAdmin

    @post = Post.new
    @post.postdate = Time.now.in_time_zone(+8.hours).strftime('%Y-%m-%d %H:%M:%S')

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @post }
    end
  end

  # GET /posts/1/edit
  def edit

    # 后台权限检测
    return unless checkAdmin

    @post = Post.find(params[:id])
    @post.postdate = @post.postdate.in_time_zone(+8.hours).strftime('%Y-%m-%d %H:%M:%S')
  end

  # POST /posts
  # POST /posts.json
  def create

    # 后台权限检测
    return unless checkAdmin

    @post = Post.new(params[:post])
    @post.postdate = @post.postdate.in_time_zone(-8.hours).strftime('%Y-%m-%d %H:%M:%S')
    @post.pic = removeDomain(@post.pic)

    respond_to do |format|
      if @post.save
        format.html { redirect_to '/admin/pagelist?notice=successfully_created' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /posts/1
  # PUT /posts/1.json
  def update

    # 后台权限检测
    return unless checkAdmin

    @post = Post.find(params[:id])

    respond_to do |format|
      @post.postdate = params[:post][:postdate]
      @post.postdate = @post.postdate.in_time_zone(-8.hours).strftime('%Y-%m-%d %H:%M:%S')
      params[:post][:postdate] = @post.postdate
      params[:post][:pic] = removeDomain(params[:post][:pic])
      if @post.update_attributes(params[:post])
        format.html { redirect_to '/admin/pagelist?notice=successfully_updated' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy

    # 后台权限检测
    return unless checkAdmin
    
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to posts_url }
      format.json { head :no_content }
    end
  end

  # GET/POST：批量发布
  def posting

    # 后台权限检测
    return unless checkAdmin

    if request.get?
      hh = (Time.now + 1.day).in_time_zone(+8.hours).strftime('%Y-%m-%d')
      stepid = 3
      @pubdates = getHH(hh, stepid)
      render :template => 'posts/post.html.erb'
    else
      count = 0 # 发布成功的个数
      content = params[:content]
      pubdate = params[:pubdate]
      arrdate = getPubDate pubdate # 获取所有日期
      #p pubdate
      #p arrdate
      #p '个数---'
      arr = content.split(/-{6,}/) # 所有的文章
      arr.each do|item|
        break unless (count < arrdate.length)
        postinfo = getPost item
        if(postinfo.size == 3)
          post = Post.new
          post.cateid = getCateid(postinfo[0]).to_i
          post.title = postinfo[1]
          post.content = getContent(postinfo[2])
          post.source = 1 # 来源于批量发布
          post.userid = session[:adminer].id
          post.userip = request.remote_ip
          post.postdate = arrdate[count]
          post.postdate = post.postdate.in_time_zone(-8.hours).strftime('%Y-%m-%d %H:%M:%S')
          count = count.next if post.save # 保存
        end
      end

      _isok = true
      render :text => if(_isok) then count.to_s else '0' end
    end
  end

private

  # 获取随机发布时间
  def getHH(date, stepNum)
    arr = []
    (5..23).each do |hh|
      if(hh %stepNum == 0)
        s = date.dup << ' ' << ("%02d" % hh) << ':' << ("%02d" % rand(60))  << ':' << ("%02d" % rand(60))
        arr << s
      end
    end
    (arr.join("\n"))
  end

  # 获取 post 类别、标题、内容
  def getPost(item)
    arr = []
    arr << item.match('[a-z]{3,}(?=:)')[0] # 类别
    arr << item.match('[a-z]{3,}:(.+)')[1] # 标题
    arr << item.match(/[a-z]{3,}:.+?[\n\r]+(.+)/m)[1] # 内容
    arr
  end

  # 获取类别id
  def getCateid(listname)
    cate = Common.getCateByUrlName(listname)
    return 0 if cate == nil
    cate.id
  end

  # 获取html格式的内容
  def getContent(content)
    content.gsub(/[\r\n]$/, '').gsub(/[\n\r]/, '<br/>')
  end

  # 获取发布日期数组
  def getPubDate(str)
    str.split(/[\n\r]+/)
  end

  ## 移除域名部分
  def removeDomain(url)
    arr = url.split(request.host_with_port)
    return arr[1] if(arr.length >= 2)
    url
  end  
end
